package com.albon.alarm;

import java.util.Timer;
import java.util.TimerTask;

import com.albon.soccer.DatabaseHelper;
import com.albon.soccer.Soccer;
import com.albon.sportsalarm.R;
import com.albon.util.AlarmAlertWakeLock;
import com.albon.util.Logg;

import android.app.Activity;
import android.content.ContentValues;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.os.SystemClock;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.TextView;

public class SoccerAlert extends Activity {
	private static final String TAG = "SoccerAlert";
	
	private int key = 1;
	private Context mContext = null;
	private static Timer mTimer;
	private long end_time = 0L;
	private Soccer soccer;
	
	private int alarm_off_time = 0;
	private String[] auto_alarm_off_time_value_array =  {};
	
	private TextView league_title;
	private TextView match_day_sub;
	private TextView match_team_sub;
	private TextView explanation_sub;
	
	private Button ok_btn;
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		mContext = this;
		final Window win = getWindow();
        win.requestFeature(Window.FEATURE_NO_TITLE);
        win.addFlags(WindowManager.LayoutParams.FLAG_SHOW_WHEN_LOCKED
                | WindowManager.LayoutParams.FLAG_TURN_SCREEN_ON );
        setContentView(R.layout.soccer_alert);
        AlarmAlertWakeLock.acquireCpuWakeLock(mContext);// 화면 깨우기
        
        key = getIntent().getIntExtra("key", 1);
        auto_alarm_off_time_value_array = getResources().getStringArray(R.array.auto_alarm_off_time_value);
        call_alarm_values(key);
        String auto_alarm_off_time_value = soccer.getAlarm_auto_off_time();
        if(auto_alarm_off_time_value==null || auto_alarm_off_time_value.equals("")){
        	alarm_off_time = 0;
        }else{
        	 alarm_off_time = Integer.parseInt(auto_alarm_off_time_value);
        }
        init();
        startTimer();
	}
	
  	private void init() {
		// TODO Auto-generated method stub
  		if(alarm_off_time!=0){
			 end_time = SystemClock.elapsedRealtime()+Integer.parseInt(auto_alarm_off_time_value_array[alarm_off_time]);
			}
  		league_title = (TextView)findViewById(R.id.league_title);
  		match_day_sub = (TextView)findViewById(R.id.match_day_sub);
  		match_team_sub = (TextView)findViewById(R.id.match_team_sub);
  		explanation_sub = (TextView)findViewById(R.id.explanation_sub);
  		ok_btn = (Button)findViewById(R.id.ok_btn);
  		ok_btn.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				activityFinish();
			}
		});
  		
  		try {
			Intent playAlarm = new Intent(SoccerAlert.this, SoccerService.class);			
			playAlarm.putExtra("key", key);
			startService(playAlarm);
		}
		catch(NullPointerException e) {
			e.printStackTrace();
		}
  		Logg.d(TAG, "soccer.getAlarm_title() : "+soccer.getAlarm_title());
  		league_title.setText(soccer.getAlarm_title());
  		match_day_sub.setText(soccer.getReal_date()+" "+soccer.getReal_time());
  		match_team_sub.setText(soccer.getA_team() + " VS "+soccer.getB_team());
  		explanation_sub.setText(soccer.getExplanation());
	}

	private void startTimer(){
		mTimer = new Timer();
		mTimer.scheduleAtFixedRate(new TimerTask()
		{
			@Override
			public void run() 
			{				
					
				if(end_time==0L){
					if (mTimer != null) {
						mTimer.cancel();
					}
				}else{
					if(end_time<=SystemClock.elapsedRealtime()){
							activityFinish();
						}
				}
					
			}
		}, 0, 1000);
	}
  	
  	private void activityFinish(){
		Logg.d(TAG, "activityFinish");
		
		stopService(new Intent(this, SoccerService.class));
		//알람 체크 박스를 풀어준다.		
		  updateAlarmOff(key);		
		AlarmAlertWakeLock.releaseCpuLock();
		
		
        if (mTimer != null) {
			mTimer.cancel();
		}
		
        
		finish();
	}
  	
  //알람 값을 불러온다.
    void call_alarm_values(int _id){
    	SQLiteDatabase databse = null;		
		if(databse == null){
			databse = openOrCreateDatabase(DatabaseHelper.DATABASE_NAME, SQLiteDatabase.CREATE_IF_NECESSARY, null);
		}
		String stringWhere = " WHERE " + DatabaseHelper.DATABASE_COLUMN_ID + " = " +_id;		
		
		Cursor cursor = null;

		try {
			cursor = databse.rawQuery("SELECT "
					+ DatabaseHelper.DATABASE_COLUMN_ID + ", "
					+ DatabaseHelper.DATABASE_COLUMN_ENABLED + ", "
					+ DatabaseHelper.DATABASE_COLUMN_REAL_DATE + ", "
					+ DatabaseHelper.DATABASE_COLUMN_REAL_TIME + ", "
					+ DatabaseHelper.DATABASE_COLUMN_COMPARE_DATE + ", "
					+ DatabaseHelper.DATABASE_COLUMN_SETTING_YEAR + ", "
					+ DatabaseHelper.DATABASE_COLUMN_SETTING_MONTH + ", "
					+ DatabaseHelper.DATABASE_COLUMN_REAGUE + ", "
					+ DatabaseHelper.DATABASE_COLUMN_STADIUM + ", "
					+ DatabaseHelper.DATABASE_COLUMN_A_TEAM + ", "
					+ DatabaseHelper.DATABASE_COLUMN_B_TEAM + ", "
					+ DatabaseHelper.DATABASE_COLUMN_SCORE + ", "
					+ DatabaseHelper.DATABASE_COLUMN_ALARM_TITLE + ", "
					+ DatabaseHelper.DATABASE_COLUMN_ALARM_RINGTONE + ", "
					+ DatabaseHelper.DATABASE_COLUMN_ALARM_VOLUME + ", "
					+ DatabaseHelper.DATABASE_COLUMN_ALARM_VIBRATE + ", "
					+ DatabaseHelper.DATABASE_COLUMN_ALARM_AUTO_OFF_TIME + ", "
					+ DatabaseHelper.DATABASE_COLUMN_SMS + ", "
					+ DatabaseHelper.DATABASE_COLUMN_VIDEO + ", "
					+ DatabaseHelper.DATABASE_COLUMN_RECORD + ", "						
					+ DatabaseHelper.DATABASE_COLUMN_HIGHLIGHT + ", "						
					+ DatabaseHelper.DATABASE_COLUMN_POWER + ", "													
					+ DatabaseHelper.DATABASE_COLUMN_NOTIFICATION + ", "													
					+ DatabaseHelper.DATABASE_COLUMN_EXPLANATION + " " + " FROM "
					+ DatabaseHelper.DATABASE_TABLE_NAME + " " + stringWhere, null);
			if (cursor != null && cursor.moveToFirst()) {
				do {
					soccer = new Soccer(cursor.getInt(0), cursor.getString(1), cursor.getString(2), cursor.getString(3), cursor.getString(4), cursor.getString(5), cursor.getString(6), cursor.getString(7), cursor.getString(8), cursor.getString(9), cursor.getString(10), cursor.getString(11), cursor.getString(12), cursor.getString(13), cursor.getString(14), cursor.getString(15), cursor.getString(16), cursor.getString(17), cursor.getString(18), cursor.getString(19), cursor.getString(20), cursor.getString(21), cursor.getString(22), cursor.getString(23));
					
					
				} while (cursor.moveToNext());
			}		
					
								
		} finally {
			if (cursor != null)
				cursor.close();
			if(databse != null){
				databse.close();
			}
		}
    }
    
    //알람을 울리고 울린알람을 다음에 울리지 안도록 업데이트 해준다.
  	public void updateAlarmOff(int key){
  		
  		SQLiteDatabase databse = null;
  		if(databse == null){
  			databse = openOrCreateDatabase(DatabaseHelper.DATABASE_NAME, SQLiteDatabase.CREATE_IF_NECESSARY, null);
  		}
  		
  		String _id = key+""; 
  		
  		ContentValues values = new ContentValues();	
  		values.put(DatabaseHelper.DATABASE_COLUMN_ENABLED, "false");  
  	
  		long uid = databse.update(DatabaseHelper.DATABASE_TABLE_NAME, values, "_id=?", new String [] {_id});
  		if(uid == -1){			
  			Logg.e(getLocalClassName(),"db update - error occurred");
  		}
  		if(databse != null){
  			databse.close();
  			databse = null;
  		}
  		
  	}
}
